<?php
class SearchesController extends AppController {

  	
    var $name = 'Searches';
    var $uses = array('Master','Vehicle','VehiclesTypes','Model','Charter','Court','Placement');
    var $helpers = array('Ajax','Time');        
    var $components = array('RequestHandler');
      
    function beforeFilter(){
    parent::beforeFilter();
    }
    
    function add2(){
            }
            
   function add(){
       $this->log($this->params['action']);
           if(!empty($this->params['action'])&& $this->params['action'] == 'index'){
           $this->log($this->params);
           //$this->redirect(array('action'=>'search'));
           }
         $this->set('title_for_layout', 'Búsquedas');
                $this->loadModel('Charter');
                $this->loadModel('Province');
                $this->loadModel('Jurisdiction');
                $this->loadModel('Placement');
                $this->loadModel('Charter');
                $this->loadModel('Court');
                $this->loadModel('Secretary');
                $this->loadModel('VehiclesType');
                $this->loadModel('PoliceStation');
                $this->loadModel('Model');
                $this->loadModel('Brand');
                
                $jurisdictions = $this->Jurisdiction->find('list',array('field'=>'descripcion'));
                $placements = $this->Placement->find('list',array('field'=>'descripcion'));
		$causes = $this->Master->Causes->find('list',array('fields'=>'nro_causa'));
		$requests = $this->Master->Requests->find('list');
		$vehicles = $this->Master->Vehicles->find('list',array('fields'=>'dominio'));
                $states = $this->Master->State->find('list');
                $desposits = $this->Master->Desposit->find('list');
                $vehicles_type = $this->VehiclesType->find('list',array('order'=>'id DESC'));
                $models = $this->Model->find('list',array('fields'=>'descripcion'));
                $brands = $this->Brand->find('list');
                $provinces = $this->Province->find('list');
                $charters = $this->Charter->find('list');
                $courts = $this->Court->find('list');
                $police_stations = $this->PoliceStation->find('list');
                $secretary = $this->Secretary->find('list');

                $this->set(compact('situations', 
                        'causes', 'requests', 'vehicles',
                        'states','desposits','vehicles_type',
                        'brands','models','jurisdictions','placements',
                        'provinces','charters','police_stations','courts','secretary'));
    
   }
  function update_select(){
             $this->loadModel('Model');
             if (!empty($this->data['Vehicles']['brands_id'])){
                        $marca_id = $this->data['Vehicles']['brands_id'];                
                        $modelos = $this->Model->find('all', array('fields'=>array('Model.id','Model.descripcion'),'order'=>'id ASC','conditions'=>array('brands_id'=>$marca_id)));
                }
             else{
                        $modelos = $this->Model->find('all', array('fields'=>array('Models.descripcion'),'order'=>'id ASC'));
                }
              $this->set('options', Set::combine($modelos, "{n}.Model.id","{n}.Model.descripcion"));
              $this->render('/searches/update_select', 'ajax');
        }
        
        function update_placements(){
          $this->loadModel('Placement');
             if (!empty($this->data['Master']['charters_id'])){
                
                   $charters_id = $this->data['Master']['charters_id'];
                   $placements = $this->Placement->find('all', array('fields'=>array('Placement.id','Placement.descripcion'),'order'=>'id ASC','conditions'=>array('charters_id'=>$charters_id)));
             }else{
                  $placements = $this->Placement->find('all', array('fields'=>array('placement.descripcion'),'order'=>'id ASC'));
             }
                $this->set('options', Set::combine($placements, "{n}.Placement.id","{n}.Placement.descripcion"));
                $this->render('/searches/update_select', 'ajax'); 
        }

        function update_provinces(){
           $this->loadModel('Charter');
           if (!empty($this->data['Master']['provinces_id'])){
                 $provinces_id = $this->data['Master']['provinces_id'];
                 $charters = $this->Charter->find('all', array('fields'=>array('Charter.id','Charter.descripcion'),'order'=>'provinces_id ASC','conditions'=>array('provinces_id'=>$provinces_id)));
           }else{
                 $charters = $this->Charter->find('all', array('fields'=>array('Charter.descripcion'),'order'=>'id ASC'));
           }
                $this->set('options', Set::combine($charters, "{n}.Charter.id","{n}.Charter.descripcion"));
                $this->render('/searches/update_select', 'ajax');
        }
        
        function update_jurisdictions(){
           $this->loadModel('Province');
           if (!empty($this->data['Master']['jurisdictions_id'])){
               $jurisdiction_id = $this->data['Master']['jurisdictions_id'];
               $provinces = $this->Province->find('all', array('fields'=>array('Province.id','Province.descripcion'),'order'=>'id ASC','conditions'=>array('jurisdiction_id'=>$jurisdiction_id)));
           }else{
               $provinces = array();    
           }                
           $this->set('options', Set::combine($provinces, "{n}.Province.id","{n}.Province.descripcion"));
           $this->render('/searches/update_select', 'ajax');
        }
        
        function update_courts(){
             $this->loadModel('Court');
             if (!empty($this->data['Master']['placements_id'])){
                   $placements_id = $this->data['Master']['placements_id'];
                   $courts = $this->Court->find('all', array('fields'=>array('Court.id','Court.descripcion'),'order'=>'length(Court.descripcion),Court.descripcion ASC','conditions'=>array('placements_id'=>$placements_id)));
             }else{
                  $courts = $this->Court->find('all', array('fields'=>array('Court.descripcion'),'order'=>'length(Court.descripcion),Court.descripcion ASC'));
             }
                $this->set('options', Set::combine($courts, "{n}.Court.id","{n}.Court.descripcion"));
                $this->render('/searches/update_select', 'ajax'); 
        } 
       
        function update_secretaries(){
             $this->loadModel('Secretary');
             if (!empty($this->data['Master']['courts_id'])){
                   $courts_id = $this->data['Master']['courts_id'];
                   $secretaries = $this->Secretary->find('all', array('fields'=>array('Secretary.id','Secretary.descripcion'),'order'=>'id ASC','conditions'=>array('courts_id'=>$courts_id)));
             }else{
                  $secretaries = $this->Secretary->find('all', array('fields'=>array('Secretary.descripcion'),'order'=>'id ASC'));
             }
                $this->set('options', Set::combine($secretaries, "{n}.Secretary.id","{n}.Secretary.descripcion"));
                $this->render('/searches/update_select', 'ajax');    
        }
      
   function index(){
       $this->set('title_for_layout', 'Búsquedas');
       $this->loadModel('Brand');
       $this->loadModel('Cause');
       $this->loadModel('Secretary');
       if($this->Session->check('conditions')){
           $conditions=$this->Session->read('conditions');
       }
               if (!empty($this->data)) {
                   $vacio = 0;
                   $datos = 0;
                   $conditions=array();
                    
                    if(!empty($this->data['Master']['secretaries_id'])||
                       !empty($this->data['Master']['jurisdictions_id'])||
                       !empty($this->data['Master']['charters_id'])||
                       !empty($this->data['Master']['placements_id'])||
                       !empty($this->data['Master']['courts_id'])){
                       $query = 'SELECT m.id, m.causes_id from masters as m INNER JOIN causes as c ON m.causes_id = c.id '; 
                      if(!empty($this->data['Master']['Causes']['secretaries_id'])){
                          $query.='INNER JOIN secretaries as s ON s.id = c.secretaries_id AND c.id = '.$this->data['Master']['secretaries_id'];
                      }else{
                          $query.='INNER JOIN secretaries as s ON s.id = c.secretaries_id '; 
                      }  
                       if(!empty($this->data['Master']['courts_id'])){
                          $query.='INNER JOIN courts as juz ON s.courts_id = juz.id AND juz.id = '.$this->data['Master']['courts_id'];   
                       }else{
                          $query.='INNER JOIN courts as juz ON s.courts_id = juz.id ';   
                       }
                       if(!empty($this->data['Master']['placements_id'])){
                          $query.=' INNER JOIN placements as circuns ON circuns.id = juz.placements_id AND juz.id = '.$this->data['Master']['placements_id'];   
                       }else{
                          $query.=' INNER JOIN placements as circuns ON circuns.id = juz.placements_id  ';   
                       }
                       if(!empty($this->data['Master']['charters_id'])){
                          $query.=' INNER JOIN charters as chart ON chart.id = circuns.charters_id AND chart.id = '.$this->data['Master']['charters_id'];   
                       }else{
                          $query.=' INNER JOIN charters as chart ON chart.id = circuns.charters_id ';   
                       }
                       if(!empty($this->data['Master']['provinces_id'])&& empty($this->data['Master']['charters_id'])){
                          $query.=' AND chart.provinces_id = '.$this->data['Master']['provinces_id'];   
                       }
                       if(!empty($this->data['Master']['jurisdictions_id'])){
                          $query.=' INNER JOIN jurisdictions as juris ON chart.jurisdictions_id = juris.id AND juris.id = '.$this->data['Master']['jurisdictions_id'];   
                       }else{
                          $query.=' INNER JOIN jurisdictions as juris ON chart.jurisdictions_id = juris.id ';   
                       }                      
                        $judiciales = $this->Master->query($query);
                            if(!empty($judiciales)) {   
                            $i=0;
                                foreach($judiciales as $judicial){
                                                $orjudiciales[$i]['Master.id'] = $judicial['m']['id'];
                                                $i++;
                                                }
                                    $totales['judiciales'] = $orjudiciales; 
                                    $datos++;
                            }else{
                                $vacio++;
                            }
                       
                    }
                    
                    $buscar = false;
                     foreach($this->data['Vehicles'] as $vehicle){
                         if($vehicle <>''){
                             $buscar=true;
                         }
                     }
                     //*****************************************VEHICULOS**************************
                    if($buscar){   
                     $query='SELECT m.id, m.vehicles_id  FROM masters as m INNER JOIN vehicles as v ON m.vehicles_id  = v.id ';
                    if(!empty($this->data['Vehicles']['nro_motor'])){
                         $query.="AND v.nro_motor LIKE '%".$this->data['Vehicles']['nro_motor']."%'"; 
                     } 
                    if(!empty($this->data['Vehicles']['nro_chasis'])){
                        $query.=" AND v.nro_chasis LIKE '%". $this->data['Vehicles']['nro_chasis']."%' ";     
                     }                        
	            if(!empty($this->data['Vehicles']['dominio'])){
                        $query.="AND v.dominio LIKE '%".$this->data['Vehicles']['dominio']."%' "; 
                     }
                    if(!empty($this->data['Vehicles']['vehicles_types_id'])){
                        $query.="AND v.vehicles_types_id = '".$this->data['Vehicles']['vehicles_types_id']."' "; 
                     }
		    if(!empty($this->data['Vehicles']['models_id'])){
                        $query.="AND v.models_id = '".$this->data['Vehicles']['models_id']."' ";  
                     }
                    if($this->data['Vehicles']['extranjero']<>''){
                        $query.="AND v.extranjero = '".$this->data['Vehicles']['extranjero']."' ";  
                     }
                    if($this->data['Vehicles']['dom_parcial']<>''){
                        $query.="AND v.dom_parcial = '".$this->data['Vehicles']['dom_parcial']."' ";  
                     }
                    if($this->data['Vehicles']['motor_parc']<>''){
                        $query.="AND v.motor_parc = '".$this->data['Vehicles']['motor_parc']."' ";  
                     }
                    if($this->data['Vehicles']['chasis_parc']<>''){
                        $query.="AND v.chasis_parc = '".$this->data['Vehicles']['chasis_parc']."' ";  
                     }
                     if(!empty($this->data['Vehicles']['brands_id'])&& empty($this->data['Vehicles']['models_id'])){
                     
                         $query.='INNER JOIN models as mo ON v.models_id = mo.id AND mo.brands_id = '.$this->data['Vehicles']['brands_id'];
                     }
                     $vehicles = $this->Master->query($query);
                        if(!empty($vehicles)) {   
                        $i=0;
                            foreach($vehicles as $vehicle){
                                        $orvehicles[$i]['Master.id'] = $vehicle['m']['id'];
                                        $i++;
                                    }
                                    $totales['vehicles'] = $orvehicles;
                                    $datos++;
                        }else{
                            $vacio++;
                        }
                     }//buscar**********************************************************************************
                     $buscar_cause = false;
                     foreach($this->data['Causes'] as $caus){
                         if($caus <>''){
                             $buscar_cause = true;
                         }
                     }
                     if($buscar_cause){
                         $query = 'SELECT m.id FROM masters AS m INNER JOIN causes as c ON c.id = m.causes_id ';
                         if(!empty($this->data['Causes']['nro_causa'])){
                             $query.="AND c.nro_causa LIKE'%".$this->data['Causes']['nro_causa']."%'";                             
                         }
                         if(!empty($this->data['Causes']['police_stations_id'])){
                             $query.="AND c.police_stations_id = ".$this->data['Causes']['police_stations_id'];
                         }
                         
                         $causes = $this->Master->query($query);
                         if(!empty($causes)){
                             $i=0;
                               foreach($causes as $cause){
                                  $orcauses[$i]['Master.id'] = $cause['m']['id'];
                                    $i++;
                                }
                               $totales['cause']=$orcauses;
                               $datos++;
                         }else{
                             $vacio++;
                         }
                        
                     }
                     ///Es para ver que datos viene de la tabla Masters para hacer las busquedas
                     $buscar_master = false;
                       if(!empty($this->data['Master']['fecha_desde']['year']) 
                       && !empty($this->data['Master']['fecha_desde']['month']) 
                       && !empty($this->data['Master']['fecha_desde']['day'])
                       && !empty($this->data['Master']['fecha_hasta']['year'])
                       && !empty($this->data['Master']['fecha_hasta']['month'])
                       && !empty($this->data['Master']['fecha_hasta']['day'])
                       ||(!empty($this->data['Master']['fecha_comp_desde']['year']) 
                       && !empty($this->data['Master']['fecha_comp_desde']['month']) 
                       && !empty($this->data['Master']['fecha_comp_desde']['day'])
                       && !empty($this->data['Master']['fecha_comp_hasta']['year'])
                       && !empty($this->data['Master']['fecha_comp_hasta']['month']) 
                       && !empty($this->data['Master']['fecha_comp_hasta']['day'])  )      
                          ){                       
                           $buscar_master = true;
                       }else{
                                    if($this->data['Master']['carpeta']<>'' 
                                       || $this->data['Master']['auditoria']<>''  
                                       || $this->data['Master']['pericia']<>''
                                       || $this->data['Master']['foto']<>''
                                       || !empty($this->data['Master']['nro_expediente'])
                                       || !empty($this->data['Master']['nro_resolucion'])
                                       || !empty($this->data['Master']['caja_archivo']) 
                                       || !empty($this->data['Master']['states_id'])
                                       || !empty($this->data['Master']['desposits_id'])
                                       || $this->data['Master']['rodamiento']<>''){
                                       $buscar_master = true;
                                         
                                    }
                       }
                     if($buscar_master){
                         $and=0;
                      $query='SELECT m.id  FROM masters as m  ';   
                    if(!empty($this->data['Master']['fecha_desde']['year']) && !empty($this->data['Master']['fecha_desde']['month']) && !empty($this->data['Master']['fecha_desde']['day'])&& !empty($this->data['Master']['fecha_hasta']['year'])&& !empty($this->data['Master']['fecha_hasta']['month'])&& !empty($this->data['Master']['fecha_hasta']['day'])){
                       
                        $query.="WHERE m.fecha between '".$this->data['Master']['fecha_desde']['year']."-".$this->data['Master']['fecha_desde']['month']."-".$this->data['Master']['fecha_desde']['day']."'and '".$this->data['Master']['fecha_hasta']['year']."-".$this->data['Master']['fecha_hasta']['month']."-".$this->data['Master']['fecha_hasta']['day']."'";
                        $and=1;
                    }
                    if(!empty($this->data['Master']['carpeta']) or $this->data['Master']['carpeta']=='0'){
                        if($and==1){$query.=' AND ';}else{$query.='WHERE ';}
                        $query.='m.carpeta = '.$this->data['Master']['carpeta'];
                        $and=1;
                        }                   
                    if(!empty($this->data['Master']['auditoria'])or $this->data['Master']['auditoria']=='0'){
                        if($and==1){$query.=' AND ';}else{$query.='WHERE ';}
                        $query.='m.auditoria = '.$this->data['Master']['auditoria'];
                        $and=1;
                        }
                   if(!empty($this->data['Master']['pericia'])or $this->data['Master']['pericia']=='0'){
                        if($and==1){$query.=' AND ';}else{$query.='WHERE ';}
                        $query.='m.pericia = '.$this->data['Master']['pericia'];
                        $and=1;
                        } 
                   if(!empty($this->data['Master']['rodamiento'])or $this->data['Master']['rodamiento']=='0'){
                        if($and==1){$query.=' AND ';}else{$query.='WHERE ';}
                        $query.='m.rodamiento = '.$this->data['Master']['rodamiento'];
                        $and=1;
                        } 
                    if(!empty($this->data['Master']['foto'])or $this->data['Master']['foto']=='0'){
                        if($and==1){$query.=' AND ';}else{$query.='WHERE ';}
                        $query.='m.foto = '.$this->data['Master']['foto'];
                        $and=1;
                        }
                    if(!empty($this->data['Master']['nro_expediente'])){
                        if($and==1){$query.=' AND ';}else{$query.='WHERE ';}
                        $query.="m.nro_expediente LIKE '%".$this->data['Master']['nro_expediente']."%'";
                        $and=1;
                        }
                    if(!empty($this->data['Master']['nro_resolucion'])){
                         if($and==1){$query.=' AND ';}else{$query.='WHERE ';}
                        $query.="m.nro_resolucion LIKE '%".$this->data['Master']['nro_resolucion']."%'";
                        $and=1;
                        }
                    if(!empty($this->data['Master']['caja_archivo'])){
                        if($and==1){$query.=' AND ';}else{$query.='WHERE ';}
                        $query.="m.caja_archivo LIKE '%".$this->data['Master']['caja_archivo']."%'";
                        $and=1;
                        } 
                    if(!empty($this->data['Master']['desposits_id'])){
                         if($and==1){$query.=' AND ';}else{$query.='WHERE ';}
                        $query.='m.desposits_id = '.$this->data['Master']['desposits_id'];
                        $and=1;
                        } 
                    if(!empty($this->data['Master']['states_id'])){
                        if($and==1){$query.=' AND ';}else{$query.='WHERE ';}
                        $query.='m.states_id = '.$this->data['Master']['states_id'];
                        $and=1;
                        }
                    if(!empty($this->data['Master']['fecha_comp_desde']['year']) && !empty($this->data['Master']['fecha_comp_desde']['month']) && !empty($this->data['Master']['fecha_comp_desde']['day'])&& !empty($this->data['Master']['fecha_comp_hasta']['year'])&& !empty($this->data['Master']['fecha_comp_hasta']['month'])&& !empty($this->data['Master']['fecha_comp_hasta']['day'])){
                        if($and==1){$query.=' AND ';}else{$query.='WHERE ';}
                         $query.="WHERE m.fecha_compactacion between '".$this->data['Master']['fecha_comp_desde']['year']."-".$this->data['Master']['fecha_comp_desde']['month']."-".$this->data['Master']['fecha_comp_desde']['day']."'and '".$this->data['Master']['fecha_comp_hasta']['year']."-".$this->data['Master']['fecha_comp_hasta']['month']."-".$this->data['Master']['fecha_comp_hasta']['day']."'";                    
                          $and=1;
                         }                     
                     
                     $mastr = $this->Master->query($query);
                     
                     if(!empty($mastr)){
                      $i=0;   
                      foreach($mastr as $mast){
                                  $ormaster[$i]['Master.id'] = $mast['m']['id'];
                                    $i++;
                                }
                     $totales['mastr']=$ormaster;
                     $datos++;
                     }else{
                         $vacio++;
                     }
                }//Buscar_master**************

          
                 if(!empty($totales) && $vacio==0){
                     $i=0;
                    foreach ($totales as $total) {
                         foreach($total as $tot){
                             $duplicados[$i]=$tot['Master.id'];
                             $i++;
                         }
                     }
                     $cantidad=0;
                     foreach($totales as $totals){                         
                              if(count($totals)>0){
                                  $cantidad++;
                              }  
                     }
                     if($cantidad >1 && $cantidad == $datos ){
                        // la funcion 'repeatedElements' devuelve los elementos duplicados y la cantidad de veces que esta duplicado
                        // de ahi elijo los elementos que mas veces este duplicado quiere decir que estaria en todos los resultados de busqueda 
                        $resultados = $this->repeatedElements($duplicados);   
                        $i=0;
                        $result4 = array();
                        $result3 = array();
                        $result2 = array();
                        foreach($resultados as $resultado){
                            if($resultado['count']==4){
                                $result4[$i] = $resultado['value']; 
                            }
                            if($resultado['count']==3){
                                $result3[$i] = $resultado['value']; 
                            }
                            if($resultado['count']==2){
                                $result2[$i] = $resultado['value']; 
                            }
                            
                            $i++;
                        }
                        $end = false;
                        if(!empty($result4)&& $datos == 4){
                                $resultados = $result4;
                                $end = true;
                            }
                        elseif(!empty($result3) && $datos == 3){
                                $resultados = $result3;
                                $end = true;
                            }
                        elseif(!empty($result2) && $datos == 2){
                                $resultados = $result2;
                                $end = true;
                            }
                            else{
                                $resultados='';
                            }
                     }elseif($cantidad == 1 && $vacio == 1 ){
                        $resultados = '';
                     
                        
                     }elseif($cantidad == 1 && $vacio == 0 ){
                         $resultados = $duplicados;
                     }else{
                         $resultados = '';
                     }
                     
                      
                     $i=0;
                     if(!empty($resultados)){
                         foreach ($resultados as $value) {
                            $result[$i]['Master.id'] = $value;
                            $i++;
                         }
                         $conditions['or'] = $result;
                        //$conditions['fields'] = array('Master.vehicles_id','Master.status_id');

                         $this->Session->write('conditions',$conditions);
                     }
   
                 }

                 
                $states = $this->Master->State->find('list');
                   if(empty($conditions)){
                      $conditions['Master.id']='---';     
                   }
                 } //if general  
                 $this->paginate = array( 
                                    'Master'   => array( 
                                    'limit'    => 10, 
                                    'page'     => 1, 
                                    'order'    => array('Master.id'    => 'asc'),
                                    'conditions' => $conditions
                                              ) 
                                ); 
                $this->set('masters',$this->paginate());
		$causes = $this->Master->Causes->find('list',array('fields'=>'nro_causa'));
		$requests = $this->Master->Requests->find('list');
                $states = $this->Master->State->find('list');
                $deposits = $this->Master->Desposit->find('list');
		$this->set(compact('situations', 'causes', 'requests', 'vehicles','states','deposits'));
	        
               
   }//metodo
  function repeatedElements($array)
 
{
    $repeated = array();
 
 
    foreach( (array)$array as $value )
    {
        $inArray = false;
 
        foreach( $repeated as $i => $rItem )
        {
            if( $rItem['value'] === $value )
            {
                $inArray = true;
                ++$repeated[$i]['count'];
            }
        }
 
        if( false === $inArray )
        {
            $i = count($repeated);
            $repeated[$i] = array();
            $repeated[$i]['value'] = $value;
            $repeated[$i]['count'] = 1;
        }
    }
 
 
    foreach( $repeated as $i => $rItem )
    {
        if($rItem['count'] === 1)
        {
            unset($repeated[$i]);
        }
    }
 
    sort($repeated);
 
    return $repeated;
 
}
public function nueva_busqueda(){
    $this->Session->delete('conditions');
    $this->redirect(array('controller' => 'searches', 'action' => 'add'));
}

}
?>
